﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SDCloudSolution.SDCloud.BusinessLayer.Model.Interfaces;
using SDCloudSolution.SDCloud.DataLayer.Model.Interfaces;
using SDCloudSolution.SDCloud.Entities;
using SDCloudSolution.SDCloud.Entities.Models;

namespace SDCloudSolution.SDCloud.BusinessLayer.Model
{
    public class ModelRunComponent : IModelRunComponent
    {
        private readonly IModelRunDataProvider _modelRunDataProvider;

        public ModelRunComponent(IModelRunDataProvider modelRunDataProvider)
        {
            _modelRunDataProvider = modelRunDataProvider;
        }

        public Task<ModelRunEntity> GetByIdAsync(int modelRunId)
        {
            if (modelRunId <= 0)
            {
                throw new ArgumentOutOfRangeException("modelRunId");
            }

            return _modelRunDataProvider.GetByIdAsync(modelRunId);
        }

        public Task<EntityCollection<ModelRunEntity>> FindByModelIdsAsync(IEnumerable<int> modelIds, Paging paging)
        {
            if (modelIds == null)
            {
                throw new ArgumentNullException("modelIds");
            }

            if (modelIds.Any())
            {
                return _modelRunDataProvider.FindByModelIdsAsync(modelIds, paging);
            }

            return Task.FromResult(new EntityCollection<ModelRunEntity>(paging));
        }

        public Task<EntityCollection<ModelRunEntity>> FindByModelIdsAndStatusesAsync(IEnumerable<int> modelIds, IEnumerable<ModelRunStatus> statuses, Paging paging)
        {
            if (modelIds == null)
            {
                throw new ArgumentNullException("modelIds");
            }

            if (statuses == null)
            {
                throw new ArgumentNullException("statuses");
            }

            if (modelIds.Any() && statuses.Any())
            {
                return _modelRunDataProvider.FindByModelIdsAndStatusesAsync(modelIds, statuses, paging);
            }

            return Task.FromResult(new EntityCollection<ModelRunEntity>(paging));
        }

        public async Task<ModelRunEntity> FindLastModelRunAsync(int modelId)
        {
            if (modelId <= 0)
            {
                return null;
            }

            return await _modelRunDataProvider.FindLastModelRunAsync(modelId);
        }

        public Task<ModelRunEntity> EnquequeModelRunAsync()
        {
            return _modelRunDataProvider.EnqueueAsync(1);
        }

        public Task UpdateModelRunAsync(ModelRunEntity entity)
        {
            return _modelRunDataProvider.UpdateAsync(entity);
        }

        public Task InsertModelRunAsync(ModelRunEntity entity)
        {
            entity.QueuedDateUtc = DateTime.UtcNow;
            return _modelRunDataProvider.InsertAsync(entity);
        }
    }
}
